/**
 * 格式化时间
 * @param {string|number|Date} time 时间
 * @param {string} format 格式
 * @returns {string} 格式化后的时间
 */
export function formatTime(time, format = 'YYYY-MM-DD HH:mm:ss') {
    if (!time) return ''

    const date = new Date(time)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()

    return format
        .replace(/YYYY/g, year)
        .replace(/MM/g, month.toString().padStart(2, '0'))
        .replace(/DD/g, day.toString().padStart(2, '0'))
        .replace(/HH/g, hour.toString().padStart(2, '0'))
        .replace(/mm/g, minute.toString().padStart(2, '0'))
        .replace(/ss/g, second.toString().padStart(2, '0'))
}

/**
 * 格式化相对时间
 * @param {string|number|Date} time 时间
 * @returns {string} 相对时间
 */
export function formatRelativeTime(time) {
    if (!time) return ''

    const now = new Date().getTime()
    const diff = now - new Date(time).getTime()

    if (diff < 0) return '刚刚'

    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour
    const week = 7 * day
    const month = 30 * day
    const year = 365 * day

    if (diff < minute) {
        return '刚刚'
    } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前'
    } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前'
    } else if (diff < week) {
        return Math.floor(diff / day) + '天前'
    } else if (diff < month) {
        return Math.floor(diff / week) + '周前'
    } else if (diff < year) {
        return Math.floor(diff / month) + '个月前'
    } else {
        return Math.floor(diff / year) + '年前'
    }
}

/**
 * 格式化数字
 * @param {number} num 数字
 * @returns {string} 格式化后的数字
 */
export function formatNumber(num) {
    if (num === null || num === undefined) return '0'

    if (num >= 100000000) {
        return (num / 100000000).toFixed(1) + '亿'
    } else if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
    } else {
        return num.toString()
    }
}

/**
 * 防抖函数
 * @param {Function} fn 要执行的函数
 * @param {number} delay 延迟时间
 * @returns {Function} 防抖后的函数
 */
export function debounce(fn, delay = 300) {
    let timer = null

    return function (...args) {
        if (timer) clearTimeout(timer)

        timer = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}

/**
 * 节流函数
 * @param {Function} fn 要执行的函数
 * @param {number} delay 延迟时间
 * @returns {Function} 节流后的函数
 */
export function throttle(fn, delay = 300) {
    let timer = null
    let lastTime = 0

    return function (...args) {
        const now = Date.now()

        if (now - lastTime >= delay) {
            fn.apply(this, args)
            lastTime = now
        } else {
            if (timer) clearTimeout(timer)

            timer = setTimeout(() => {
                fn.apply(this, args)
                lastTime = Date.now()
            }, delay - (now - lastTime))
        }
    }
}

/**
 * 获取随机颜色
 * @returns {string} 随机颜色
 */
export function getRandomColor() {
    return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')
}

/**
 * 复制文本到剪贴板
 * @param {string} text 要复制的文本
 * @returns {Promise} Promise对象
 */
export function copyToClipboard(text) {
    return new Promise((resolve, reject) => {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text)
                .then(() => resolve(true))
                .catch(err => reject(err))
        } else {
            const textarea = document.createElement('textarea')
            textarea.value = text
            textarea.style.position = 'fixed'
            textarea.style.opacity = '0'
            document.body.appendChild(textarea)
            textarea.select()

            try {
                document.execCommand('copy')
                document.body.removeChild(textarea)
                resolve(true)
            } catch (err) {
                document.body.removeChild(textarea)
                reject(err)
            }
        }
    })
}

/**
 * 获取图片的主色调
 * @param {string} imgUrl 图片地址
 * @returns {Promise<string>} 主色调
 */
export function getImageMainColor(imgUrl) {
    return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'Anonymous'
        img.src = imgUrl

        img.onload = function () {
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')
            canvas.width = img.width
            canvas.height = img.height

            ctx.drawImage(img, 0, 0, img.width, img.height)

            const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data
            const colorCount = {}

            for (let i = 0; i < imageData.length; i += 4) {
                const r = imageData[i]
                const g = imageData[i + 1]
                const b = imageData[i + 2]
                const rgb = `rgb(${r},${g},${b})`

                if (colorCount[rgb]) {
                    colorCount[rgb]++
                } else {
                    colorCount[rgb] = 1
                }
            }

            let maxCount = 0
            let mainColor = ''

            for (const color in colorCount) {
                if (colorCount[color] > maxCount) {
                    maxCount = colorCount[color]
                    mainColor = color
                }
            }

            resolve(mainColor)
        }

        img.onerror = function (err) {
            reject(err)
        }
    })
}

/**
 * 生成唯一ID
 * @returns {string} 唯一ID
 */
export function generateUniqueId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
}

/**
 * 获取URL参数
 * @param {string} name 参数名
 * @returns {string|null} 参数值
 */
export function getUrlParam(name) {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    const r = window.location.search.substr(1).match(reg)
    if (r != null) return decodeURIComponent(r[2])
    return null
}

/**
 * 判断是否是移动设备
 * @returns {boolean} 是否是移动设备
 */
export function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

/**
 * 获取设备类型
 * @returns {string} 设备类型
 */
export function getDeviceType() {
    const ua = navigator.userAgent
    if (/iPad/i.test(ua)) return 'iPad'
    if (/iPhone/i.test(ua)) return 'iPhone'
    if (/Android/i.test(ua)) return 'Android'
    if (/Windows Phone/i.test(ua)) return 'Windows Phone'
    return 'Desktop'
} 